package com.leave.web.servlet;

import com.leave.context.AppContext;
import com.leave.entity.Admin;
import com.leave.entity.Classes;
import com.leave.entity.Department;
import com.leave.service.AdminService;
import com.leave.service.DepartmentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@WebServlet(name = "adminServlet", urlPatterns = {"/admin"})
public class AdminServlet extends HttpServlet {
    private final static String DEPART_LIST = "department_list.jsp";
    private final static String ADMIN_LIST = "admin_individual.jsp";
    private final Logger logger = LoggerFactory.getLogger(LeaveServlet.class);
    private DepartmentService departmentService;
    private AdminService adminService;
    @Override
    public void init() throws ServletException {
        super.init();
        //从IoC容器获取实例化bean组件
       departmentService = AppContext.getBean(DepartmentService.class);
        adminService = AppContext.getBean(AdminService.class);

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        logger.info("request process starting" + action);
        String depID=request.getParameter("depID");
        String depName=request.getParameter("depName");
        String keyword = request.getParameter("keyword");
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "adminList":
                    List<Admin> adiminList = adminService.adminList(null);
                    session.setAttribute("list", adiminList);
//                    System.out.println(3_1);
                    request.getRequestDispatcher(ADMIN_LIST).forward(request, response);
                    break;
                case "list":
                    List<Department> departmentList=departmentService.departmentList(null);
                    session.setAttribute("list", departmentList);
//                    System.out.println(3_1);
                    request.getRequestDispatcher(DEPART_LIST).forward(request, response);
                    break;
                case "seek":
//                    System.out.println("depID " + depID);
                    try {
                        List<Map<String, Object>> departmentList1 = departmentService.seek(keyword);
                        session.setAttribute("list", departmentList1);
                        request.getRequestDispatcher(DEPART_LIST).forward(request, response);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    break;
                case  "delete":
//                    System.out.println("depID " + depID);
                    departmentService.deleteDep(depID);
                    request.getRequestDispatcher("admin?action=list").forward(request, response);
                    break;
                case "add":
                    Department department = new Department();
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(request,department);
                    //调用service组件完成数据写入
                    boolean successA = departmentService.addDep(department);
                    if (successA) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "二级学院信息添加成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "二级学院信息添加失败，请重试！");
                    }
                    //指定跳转路径
                    request.getRequestDispatcher("admin?action=list").forward(request, response);
                    break;
                case "adminEdit":
                    Admin admin = new Admin();
                    resolveRequestParameter(request,admin);
//                    System.out.println("daozheli");
                    boolean successAE = adminService.editAdmin(admin);
                    if (successAE) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "个人信息修改成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "个人信息修改失败，请重试！");
                    }
                    request.getRequestDispatcher("admin?action=adminList").forward(request, response);
                    break;
                case "edit":
                    System.out.println(depID+depName);
                    Department department1=new Department();
                    System.out.println(1234);
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(request,department1);
                    //调用service组件完成数据写入
                    boolean successDE = departmentService.editDep(department1);
                    if (successDE) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "二级学院信息修改成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "二级学院信息修改失败，请重试！");
                    }
                    request.getRequestDispatcher("admin?action=list").forward(request, response);
                    break;
            }

        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void resolveRequestParameter(HttpServletRequest req,Object bean){
        Map<String,String[]> reqParameterMap= req.getParameterMap();
        Map<String,String[]> propertiesMap=new HashMap<String,String[]>();
        try {
            for (Map.Entry<String,String[]>  entry : reqParameterMap.entrySet()){
                String name =entry.getKey();
                String[] values=entry.getValue();
                //判断request参数是否对应JavaBean对象的属性
                Class propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType!=null) {
                    propertiesMap.put(name,values);
                }
            }
            //转换为POJO对象bean的属性值
            BeanUtils.populate(bean,propertiesMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("The property name could not be found",e);
        }
    }

}
